﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Web;
using Admin.NET.Core;

namespace Admin.NET.Application
{
    /// <summary>
    /// 库口表服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsWarehouseEntrance", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsWarehouseEntranceService : IDynamicApiController, ITransient
    {
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly IRepository<WmsWarehouseEntrance, MasterDbContextLocator> _wareWarehouseEntranceRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysDictTypeRep"></param>
        /// <param name="sysDictDataRep"></param>
        /// <param name="wareWarehouseEntranceRep"></param>

        /// <param name="sysExcelTemplateService"></param>
        public WmsWarehouseEntranceService(
            IRepository<WmsWarehouseEntrance, MasterDbContextLocator> wareWarehouseEntranceRep,
            IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep,
            IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep,
            ISysExcelTemplateService sysExcelTemplateService
        )
        {
            _sysDictTypeRep = sysDictTypeRep;
            _sysDictDataRep = sysDictDataRep;
            _wareWarehouseEntranceRep = wareWarehouseEntranceRep;
            _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 分页查询库口表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsWarehouseEntranceOutput>> Page([FromQuery] WareWarehouseEntranceSearch input)
        {
            var wareWarehouseEntrances = await _wareWarehouseEntranceRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.Name), u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.Code), u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%"))
                .Where(input.Type != null, u => u.Type == input.Type)
                .Where(input.LesWorkShopType != null, u => u.LesWorkShopType == input.LesWorkShopType)
                .OrderBy(PageInputOrder.OrderBuilder<WareWarehouseEntranceSearch>(input))
                .ProjectToType<WmsWarehouseEntranceOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wareWarehouseEntrances;
        }

        /// <summary>
        /// 不分页查询库口表列表
        /// </summary>
        /// <param name="input">库口表查询参数</param>
        /// <returns>(库口表)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsWarehouseEntranceOutput>> ListNonPageAsync([FromQuery] WareWarehouseEntranceSearchNonPage input)
        {
            var pName = input.Name?.Trim() ?? "";
            var pCode = input.Code?.Trim() ?? "";
            var pType = input.Type;
            var pLesWorkShopType = input.LesWorkShopType;
            var wareWarehouseEntrances = await _wareWarehouseEntranceRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pName), u => EF.Functions.Like(u.Name, $"%{pName}%"))
                .Where(!string.IsNullOrEmpty(pCode), u => EF.Functions.Like(u.Code, $"%{pCode}%"))
                .Where(pType != null, u => u.Type == pType)
                .Where(pLesWorkShopType != null, u => u.LesWorkShopType == pLesWorkShopType)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsWarehouseEntranceOutput>()
            .ToListAsync();
            return wareWarehouseEntrances;
        }

        /// <summary>
        /// 增加库口表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWareWarehouseEntranceInput input)
        {
            var wareWarehouseEntrance = input.Adapt<WmsWarehouseEntrance>();
            await _wareWarehouseEntranceRep.InsertAsync(wareWarehouseEntrance);
        }

        /// <summary>
        /// 删除库口表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWareWarehouseEntranceInput input)
        {
            var wareWarehouseEntrance = await _wareWarehouseEntranceRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wareWarehouseEntranceRep.DeleteAsync(wareWarehouseEntrance);
        }

        /// <summary>
        /// 更新库口表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWareWarehouseEntranceInput input)
        {
            var isExist = await _wareWarehouseEntranceRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wareWarehouseEntrance = input.Adapt<WmsWarehouseEntrance>();
            await _wareWarehouseEntranceRep.UpdateAsync(wareWarehouseEntrance, ignoreNullValues: true);
        }

        /// <summary>
        /// 获取库口表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsWarehouseEntranceOutput> Get([FromQuery] QueryeWareWarehouseEntranceInput input)
        {
            return (await _wareWarehouseEntranceRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsWarehouseEntranceOutput>();
        }

        /// <summary>
        /// 获取库口表列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsWarehouseEntranceOutput>> List([FromQuery] WmsWarehouseEntranceInput input)
        {
            return await _wareWarehouseEntranceRep.DetachedEntities.ProjectToType<WmsWarehouseEntranceOutput>().ToListAsync();
        }

        /// <summary>
        /// Excel模板导入库口表功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareWarehouseEntrance", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++)
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsWarehouseEntranceOutput> wareWarehouseEntranceList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsWarehouseEntranceOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wareWarehouseEntranceList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsWarehouseEntrance>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if (!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsWarehouseEntrance, WmsWarehouseEntranceOutput>(selectKeys);
            List<WmsWarehouseEntrance> updates = new();
            List<WmsWarehouseEntrance> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wareWarehouseEntranceExistSubList = _wareWarehouseEntranceRep.Where(filter).Select(selector).ToList();
                    wareWarehouseEntranceExistSubList.ForEach(x =>
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }

                foreach (var wareWarehouseEntrance in wareWarehouseEntranceList)
                {
                    if (wareWarehouseEntrance.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wareWarehouseEntrance.Adapt<WmsWarehouseEntrance>());
                    }
                    else
                    {
                        adds.Add(wareWarehouseEntrance.Adapt<WmsWarehouseEntrance>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wareWarehouseEntranceRep.Update(x));

                var maxId = _wareWarehouseEntranceRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);
                Db.GetDbContext().Set<WmsWarehouseEntrance>().AddRange(adds);
                Db.GetDbContext().SaveChanges();
            }

            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载库口表的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareWarehouseEntrance", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }

        /// <summary>
        /// 根据库口表查询参数导出Excel
        /// </summary>
        /// <param name="input">库口表查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WareWarehouseEntranceSearchNonPage input)
        {
            var wareWarehouseEntranceList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wareWarehouseEntranceList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers,
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareWarehouseEntrance", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
